package com.qen.jiaoyu.zhouyi

import cn.hutool.core.lang.Console
import cn.hutool.core.util.CharsetUtil
import cn.hutool.core.util.StrUtil
import cn.hutool.poi.excel.ExcelUtil
import com.qen.jiaoyu.songci.spliceHtml
import it.skrape.core.htmlDocument
import it.skrape.fetcher.BrowserFetcher
import it.skrape.fetcher.Method
import it.skrape.fetcher.response
import it.skrape.fetcher.skrape
import nl.siegmann.epublib.domain.Author
import nl.siegmann.epublib.domain.Book
import nl.siegmann.epublib.domain.Resource
import nl.siegmann.epublib.domain.Resources
import nl.siegmann.epublib.epub.EpubWriter
import nl.siegmann.epublib.service.MediatypeService
import java.io.File
import java.io.FileOutputStream
import kotlin.collections.forEach

const val ShiCiUrl = "https://www.diyifanwen.com/guoxue/zhouyi/"
const val UserAgent =
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
const val ShiCiExcelPath = "/Users/a1/Documents/Git/Kotlin/Eleven/out/jiaoyu"
fun main() {
    val list = arrayListOf<ShiCi>()
    var resources: Resources = Resources()
    var book: Book = Book()
    book.metadata.addTitle("周易")
    book.metadata.addAuthor(Author("MayBeTheGo"))
    for (i in 1..3) {
        val goUrl = if (i == 1) ShiCiUrl else "${ShiCiUrl}index_$i.html"
        Console.log(goUrl)
        try {
            skrape(BrowserFetcher) {
                request {
                    url = goUrl
                    headers = initHeader()
                    cookies = initCookie()
                    userAgent = UserAgent
                    method = Method.GET
                    body = null
                    this.timeout = 10000
                    charset(CharsetUtil.GBK)
                }
                response {
                    htmlDocument {
                        ".alllist-data" {

                            findAll {

                                val div = this.first()

                                val ul = div.children.first()

                                ul.children.forEach { li ->
                                    val a = li.children.first()
                                    val href = a.attribute("href")
                                    val text = a.text
                                    val sc = ShiCi(title = text, author = "", url = "https:$href")
                                    list.add(sc)
                                    Console.log(sc)
                                }

                            }

                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    for (i in 1..list.size - 1) {
        val obj = list.get(i)
        shiCiContent(obj.url, obj.title, resources, book)
    }
    val outputFile = File("$ShiCiExcelPath/周易.epub")
    val outputStream = FileOutputStream(outputFile)
    EpubWriter().write(book, outputStream)
    outputStream.close()

    val writer = ExcelUtil.getWriter("$ShiCiExcelPath/周易.xlsx")
    writer.passCurrentRow()
    writer.write(list, true)
    writer.close()
}

fun initHeader(): MutableMap<String, String> {
    return mutableMapOf(
        "accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "accept-language" to "zh-CN,zh;q=0.9,en;q=0.8",
        "cache-control" to "no-cache",
        "pragma" to "no-cache",
        "sec-ch-ua" to "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
        "sec-ch-ua-mobile" to "?0",
        "sec-ch-ua-platform" to "\"macOS\"",
        "sec-fetch-dest" to "document",
        "sec-fetch-mode" to "navigate",
        "sec-fetch-site" to "same-origin",
        "sec-fetch-user" to "?1",
        "upgrade-insecure-requests" to "1",
        "accept-encoding" to "utf-8"
    )
}

fun initCookie(): MutableMap<String, String> {
    return mutableMapOf(
        "SetCookieTF" to "1",
        "testcookie" to "yes",
        "Hm_lvt_3a5e11b41af918022c823a8041a34e78" to "1729817592",
        "HMACCOUNT" to "8E7727E55235B30C",
        "DYFWUID" to "17298176038533kc8cgdfyo8q0u6",
        "Hm_lpvt_3a5e11b41af918022c823a8041a34e78" to "1729818055",
    )
}

public data class ShiCi(
    val title: String,
    val author: String,
    val url: String,
)

fun shiCiContent(goUrl: String, title: String, resources: Resources, book: Book) {
    try {
        skrape(BrowserFetcher) {
            request {
                url = goUrl
                headers = initHeader()
                cookies = initCookie()
                userAgent = UserAgent
                method = Method.GET
                body = null
                this.timeout = 10000
                charset(CharsetUtil.GBK)
            }
            response {
                htmlDocument {
                    ".content" {
                        findAll {
                            val div = this.get(0)
                            val html = spliceHtml("${div.html}")
                            val p = StringBuilder()
                            html.forEach { string ->
                                if (StrUtil.isNotBlank(string.trim())) {
                                    p.append("<p>${string.trim()}</p>")
                                }
                            }
                            val template = """
                                            <?xml version="1.0" encoding="UTF-8"?>
                                            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
                                            <html xmlns="http://www.w3.org/1999/xhtml">
                                            <head>
                                                <title>${title}</title>
                                            </head>
                                            <body>
                                                <h1>${title}</h1>
                                                $p
                                            </body>
                                            </html>
                                        """.trimIndent()
                            val chapter1Resource =
                                Resource(template.toByteArray(), "${System.currentTimeMillis()}.xhtml")
                            chapter1Resource.mediaType = MediatypeService.XHTML
                            resources.add(chapter1Resource)
                            book.addSection(title, chapter1Resource)
                        }
                    }
                }
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

}
